package com.jjlin.web;

import com.jjlin.entity.Blog;
import com.jjlin.entity.Type;
import com.jjlin.service.BlogService;
import com.jjlin.service.TypeService;
import com.jjlin.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

@Controller
public class TypeShowController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private BlogService blogService;

    @GetMapping("/types/{id}")
    public String types(@PageableDefault(size = 6, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                        @PathVariable Long id, Model model) {
        List<Type> types = typeService.listTypeTop(10000);//以博客数量进行倒序查询
        for(Type type: types){//获取该分类中已经发布的博客数量
            long count = 0;
            List<Blog> blogs = type.getBlogs();
            for(Blog blog: blogs)
                if(blog.isPublished())
                    count++;
            type.setPublishedBlogCount(count);
        }
        if (id == -1) {
            id = types.get(0).getId();
        }
        model.addAttribute("types", types);
        model.addAttribute("page", blogService.listBlogByTypeId(id, pageable));
        model.addAttribute("activeTypeId", id);
        return "types";
    }
}
